package model

import (
	"gin-jwt-test/db"
	"gin-jwt-test/utils"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"log"
	"strconv"
	"time"
)

type User struct {
	gorm.Model
	UUID     string `json:"-"`        // 唯一标识符号
	Username string `json:"username"` // 登录名，例如annter
	Password string `json:"password"` // 密码
	Salt     string `json:"-"`
}

func (u *User) Create(username, pwd string) (User, error) {
	var us User
	if err := db.MySql().AutoMigrate(User{}); err != nil {
		log.Fatalln(err)
		return us,err
	}
	generateUUID := uuid.New().String()
	salt := strconv.FormatInt(time.Now().Unix(), 10)
	password := utils.HashMd5("." + pwd + "xtsci" + salt + ".")
	us = User{
		UUID:     generateUUID,
		Salt:     salt,
		Password: password,
		Username: username,
	}
	err := db.MySql().Create(&us).Error
	if err != nil {
		log.Fatalln(err)
		return us, err
	}
	return us, nil
}

// 查找query
func (u *User) Query(username string) (User, error) {
	var result User
	err := db.MySql().
		Debug().
		Where("username = ?", username).
		Find(&result).Error
	if err != nil {
		log.Fatal(err)
		return result, err
	}
	return result, nil
}
